package com.aaa.servlet;

import com.aaa.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @program: gz01-web
 * @description:
 * @author: 闫克起2
 * @create: 2023-09-14 11:31
 **/
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private UserDao userDao=new UserDao();

    //处理前端的get和post请求方式
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受账号和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2. 调用UserDao对象中的方法
        Map<String, Object> map = userDao.findByUsernameAndPwd(username, password);
        //3. 判断返回的结果是否正确
        if(map!=null){
             //表示登录成功
            //获取session对象
            HttpSession session = req.getSession();
            //把用户信息保存到session中---判断用户是否登录过. 只要浏览器部关闭--session中存储的内容就一直存在。
            session.setAttribute("user",map);
            resp.sendRedirect("/main.jsp"); //重定向页面跳转
        }else{
             req.setAttribute("msg","<font color='red'>账号或密码错误</font>");
             //表示登录失败
             req.getRequestDispatcher("/Login.jsp").forward(req,resp);//转发跳转。
        }
    }


}
